<template>
  <div>
    <!-- 面包屑导航区  -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button
            style="float: right"
            type="primary"
            @click="rolesDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="rolesDialogVisible"
        width="40%"
      >
        <!-- 添加内容主体区 -->
        <el-form
          :model="addRolesForm"
          ref="addRolesFormRef"
          label-width="80px"
          :rules="rolesFormRules"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column label="展开" type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdrowbottom', i1 === 0 ? 'bdrowtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRolesRights(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 嵌套渲染二级权限 -->
                <el-row
                  :gutter="10"
                  :class="['bdrowleft', i2 === 0 ? '' : 'bdrowtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRolesRights(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRolesRights(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改信息"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showRoles(scope.row.id)"
              >
              </el-button>
            </el-tooltip>

            <!-- 修改角色对话框 -->
            <el-dialog
              title="修改角色"
              :visible.sync="altRolesDialogVisible"
              width="40%"
            >
              <!-- 修改内容主体区 -->
              <el-form
                :model="altRolesForm"
                ref="altRolesFormRef"
                label-width="80px"
                :rules="rolesFormRules"
              >
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="altRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                  <el-input v-model="altRolesForm.roleDesc"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="altRolesDialogVisible = false"
                  >取 消</el-button
                >
                <el-button type="primary" @click="subAltRoles">确 定</el-button>
              </span>
            </el-dialog>

            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除信息"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                style="margin-left: 4px"
                @click="removeRoleById(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配权限按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="distbRolesDialog(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 分配权限对话框 -->
            <el-dialog
              title="分配权限"
              :visible.sync="distbRolesDialogVisible"
              width="40%"
              @close="resetRolesRights"
            >
              <!-- 树形控件 -->
              <el-tree
                :data="rightsList"
                :props="rolesTreeProps"
                ref="rightsRef"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="rightsKeys"
              ></el-tree>

              <span slot="footer" class="dialog-footer">
                <el-button @click="distbRolesDialogVisible = false"
                  >取 消</el-button
                >
                <el-button type="primary" @click="allotRolesRights"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色列表的数据
      rolesList: [],
      //权限列表
      rightsList: [],
      //添加角色的数据
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      //保存修改后的用户数据
      altRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      //控制添加角色对话框的显示与隐藏
      rolesDialogVisible: false,
      //控制修改角色对话框的显示与隐藏
      altRolesDialogVisible: false,
      //控制分配权限对话框的显示与隐藏
      distbRolesDialogVisible: false,
      //添加验证规则
      rolesFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //树形控件的绑定对象
      rolesTreeProps: {
        label: "authName",
        children: "children",
      },
      //默认选中的权限id
      rightsKeys: [],
      //即将被分配权限的id值
      roleId: "",
    };
  },
  created() {
    //刷新网页时就加载所有数据
    this.getRolesList();
  },
  methods: {
    //请求角色所有数据
    async getRolesList() {
      //请求角色列表数据
      const { data: res } = await this.$http.get("roles");
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data;
    },
    //添加角色时请求数据
    addRoles() {
      this.$refs.addRolesFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addRolesForm);
        if (res.meta.status !== 201) {
          return this.$message.error("角色数据请求失败！");
        }
        //关闭对话框时隐藏对话框
        this.rolesDialogVisible = false;
        //刷新数据
        this.getRolesList;
        //提示添加成功
        this.$message.success("添加角色成功！");
      });
    },
    //显示当前ID角色的信息
    async showRoles(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色失败！");
      }
      //将服务器的数据保存到data中的altRolesForm中
      this.altRolesForm = res.data;
      //点击修改角色时显示对话框
      this.altRolesDialogVisible = true;
    },
    //提交修改后的用户数据
    subAltRoles() {
      this.$refs.altRolesFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `roles/${this.altRolesForm.roleId}`,
          {
            roleName: this.altRolesForm.roleName,
            roleDesc: this.altRolesForm.roleDesc,
          }
        );
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error("获取角色数据失败！");
        }
        //关闭对话框时隐藏对话框
        this.altRolesDialogVisible = false;
        //刷新角色数据
        this.getRolesList();
        //提示用户修改成功
        this.$message.success("修改角色成功！");
      });
    },
    //删除当前ID的角色
    async removeRoleById(id) {
      //弹框询问用户是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmResult);
      //如果用户确认删除，则返回字符串confirm
      //如果用户取消删除，着返回字符串cancel
      if (confirmResult == "cancel") {
        return this.$message.info("已经取消删除！");
      }
      //请求角色数据
      const { data: res } = await this.$http.delete(`roles/${id}`);
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色数据失败！");
      }
      //刷新数据
      this.getRolesList();
      //提示用户删除角色成功
      this.$message.success("删除角色成功！");
    },
    //移除角色权限
    async removeRolesRights(role, rightId) {
      //弹框提示用户是否要执行该行为
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmResult);
      //如果用户确认删除，则返回字符串confirm
      //如果用户取消删除，着返回字符串cancel
      if (confirmResult == "cancel") {
        return this.$message.info("已经取消删除！");
      }
      //请求数据
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      //   console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("删除权限失败！");
      }
      //重新赋值权限
      role.children = res.data;
      //提示用户
      this.$message.success("删除权限成功！");
    },
    //展示分配权限的对话框
    async distbRolesDialog(role) {
      this.roleId = role.id;
      //请求权限数据
      const { data: res } = await this.$http.get(`rights/tree`);
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据失败！");
      }
      //把权限数据存放到data的rightsList中
      this.rightsList = res.data;
      //拿到权限数组的每一个对象的ID
      this.getRolesRights(role, this.rightsKeys);
      //显示权限对话框
      this.distbRolesDialogVisible = true;
    },
    //通过递归形式获取角色下所有三级权限的id，并保存到rightsKeys中
    getRolesRights(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getRolesRights(item, arr));
    },
    //重置权限对话框
    resetRolesRights() {
      this.rightsKeys = [];
    },
    //分配角色权限
    async allotRolesRights() {
      const keys = [
        ...this.$refs.rightsRef.getCheckedKeys(),
        ...this.$refs.rightsRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败！");
      }
      //刷新数据
      this.getRolesList();
      //提示
      this.$message.success("分配权限成功！");
      //隐藏对话框
      this.distbRolesDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdrowtop {
  border-top: 1px solid #eee;
}
.bdrowbottom {
  border-bottom: 1px solid #eee;
}
.bdrowleft {
  border-left: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
